package com.item.action;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpSession;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.base.Page;
import com.base.dialect.PaginationSupport;
import com.base.util.JSONUtils;
import com.item.dao.model.Admin;
import com.item.dao.model.AdminExample;
import com.item.dao.model.Book;
import com.item.dao.model.BookExample;
import com.item.dao.model.Cart;
import com.item.dao.model.CartKey;
import com.item.dao.model.Order;
import com.item.dao.model.OrderExample;
import com.item.dao.model.OrderItem;
import com.item.dao.model.OrderItemExample;
import com.item.dao.model.User;
import com.item.daoEx.OrderEx;
import com.item.daoEx.Ret;
import com.item.daoEx.model.CartEx;
import com.item.daoEx.model.CartList;
import com.item.exception.ActionException;
import com.item.exception.JSONRepUtils;
import com.item.service.AdminService;
import com.item.service.BookService;
import com.item.service.CartService;
import com.item.service.OrderItemService;
import com.item.service.OrderService;
import com.item.service.UserService;

@Controller
public class OrderController {
	@Autowired
	private OrderService orderService;
	@Autowired
	private BookService bookService;
	@Autowired
	private OrderItemService orderItemService;
	@Autowired
	private CartService cartService;
	@Autowired
	private UserService userService;
	@Autowired
	private AdminService adminService;

	@RequestMapping("/listOrder")
	@ResponseBody
	public String list(Page param, Order order, Integer isNotPage, Integer isM, HttpSession session) throws Exception{
		Object objForSer = null;
		OrderExample example = new OrderExample();
		PaginationSupport.setContext(param.getPageStart(), param.getPageSize(), null);
		OrderExample.Criteria criteria = example.createCriteria();
		String appid = (String)session.getAttribute("appid");
		if(StringUtils.isNotBlank(appid) && !appid.equals("all")) {
			criteria.andSidEqualTo(appid);
		}
		if(StringUtils.isNotBlank(order.getsName()) && appid.equals("all")) {
			criteria.andSNameLike("%" + order.getsName() + "%");
		}
		if(StringUtils.isNotBlank(order.getUserid())) {
			criteria.andUseridEqualTo(order.getUserid());
		}
		if(StringUtils.isNotBlank(order.getUsername())) {
			criteria.andUsernameLike("%" + order.getUsername() + "%");
		}
		if(StringUtils.isNotBlank(order.getPhone())) {
			criteria.andPhoneLike("%" + order.getPhone() + "%");
		}
		if(StringUtils.isNotBlank(order.getAddress())) {
			criteria.andAddressLike("%" + order.getAddress() + "%");
		}
		if(order.getStatus() != null) {
			criteria.andStatusEqualTo(order.getStatus());
		}
		criteria.andUseridIsNotNull();
		if(isM == null || isM == 0)
			example.setOrderByClause("status ASC, create_time DESC");
		else
			example.setOrderByClause("create_time DESC");
		List<Order> list = orderService.selectByExample(example);

		if(isNotPage != null && isNotPage == 1) {
			objForSer = list;
		} else {
			List<OrderEx> listEx = new ArrayList<OrderEx>();
			for(Order o : list) {
				OrderEx oEx = new OrderEx(o);
				OrderItemExample orderItemExample = new OrderItemExample();
				orderItemExample.createCriteria().andOrderidEqualTo(o.getId());
				oEx.setItems(orderItemService.selectByExample(orderItemExample));
				listEx.add(oEx);
			}
			
			objForSer = new Page(PaginationSupport.getContext().getTotalCount(), listEx);
		}
		
		return JSONRepUtils.serialize(objForSer, isM);
	}
	
	@RequestMapping("/showlistOrder")
	public String list() {
		return "order/orderList";
	}
	
	@RequestMapping("/toEditOrder")
	public String toEdit()throws Exception{
		return "order/orderDetail";
	}
	
	@RequestMapping("/listOrderItem")
	@ResponseBody
	public String listItem(Page param, Integer orderid, Integer isNotPage, Integer isM) throws Exception {
		Object objForSer = null;
		OrderItemExample example = new OrderItemExample();
		PaginationSupport.setContext(param.getPageStart(), param.getPageSize(), null);

		example.createCriteria().andOrderidEqualTo(orderid);
		example.setOrderByClause("create_time DESC");
		List<OrderItem> list = orderItemService.selectByExample(example);
		
		if(isNotPage != null && isNotPage == 1) {
			objForSer = list;
		} else {
			objForSer = new Page(PaginationSupport.getContext().getTotalCount(), list);
		}
		
		return JSONRepUtils.serialize(objForSer, isM);
	}
	
	/**
	 * userid前端传输
	 * @param order
	 * @param cartIds
	 * @param isM
	 * @param session
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="/saveOrder")
	@ResponseBody
	public String save(Order order, String bookids, Integer isM, HttpSession session) throws Exception{
		if(StringUtils.isBlank(order.getUserid())) {
			throw new ActionException("userid");
		}
		if(StringUtils.isBlank(bookids)) {
			throw new ActionException("bookids");
		}
		
		CartList ret = new CartList();
		User user = userService.selectByPrimaryKey(order.getUserid());
		
		if(order.getId() == null) {		
			order.setCreateTime(new Date());
			order.setAddress(user.getAddress());
			order.setPhone(user.getPhone());
			order.setUsername(user.getName());
			order.setsName(user.getsName());
			order.setSid(user.getSid());
			order.setStatus(0);
			int rows = orderService.insertSelective(order);
			
			if(rows > 0) {
				String[] bids = bookids.split(",");
				for(String bid : bids) {
					CartKey key = new CartKey();
					key.setBookid(bid);
					key.setUserid(order.getUserid());
					Cart cart = cartService.selectByPrimaryKey(key);
					if(cart != null)
						createOrder(order.getId(), cart.getCount(), bid, ret, key);		
				}
				if(ret.getCarts().size() == bids.length) {
					orderService.deleteByPrimaryKey(order.getId());
					ret.setSuccess(false);
				} else
					ret.setSuccess(true);
			}
		} else {
			order.setModifyTime(new Date());
			int rows = orderService.updateByPrimaryKeySelective(order);
			if(rows > 0)
				ret.setSuccess(true);
		}
		
		return JSONRepUtils.serialize(ret, isM);
	}
	
	@RequestMapping(value="/buyDirect")
	@ResponseBody
	public String saveItems(String bookid, String userid, Integer isM, HttpSession session) throws Exception{ 
		CartList ret = new CartList();
		
		if(StringUtils.isBlank(userid)) {
			throw new ActionException("userid");
		}
		if(StringUtils.isBlank(bookid)) {
			throw new ActionException("bookid");
		}
		
		int orderid = orderService.createNewOrder(userid);
		
		if(orderid >= 0) {
			String[] bids = bookid.split(",");
			for(String bid : bids) {
				createOrder(orderid, 1, bid, ret, null);
			}
			if(ret.getCarts().size() == bids.length) {
				orderService.deleteByPrimaryKey(orderid);
				ret.setSuccess(false);
			} else
				ret.setSuccess(true);
		}
		
		return JSONRepUtils.serialize(ret, isM);
	}
	
	@RequestMapping(value="/saveOrderDirect")
	@ResponseBody
	public String saveItem(OrderItem orderItem, String userid, Integer isM, HttpSession session) throws Exception{
		Ret ret = new Ret();
		CartList cl = new CartList();
		if(StringUtils.isBlank(userid)) {
			throw new ActionException("userid");
		}
		int orderid = this.orderService.createNewOrder(userid);
		if(orderid > 0) {
			createOrder(orderid, orderItem.getCount(), orderItem.getBookid(), cl, null);
			if(cl.getCarts().size() == 0)
				ret.setSuccess(true);
			else {
				orderService.deleteByPrimaryKey(orderid);
			}
		}
		
		return JSONRepUtils.serialize(ret, isM);
	}
	
	/**
	 * 添加订单单项到指定订单
	 * @param orderid
	 * @param count
	 * @param bid
	 * @param ret
	 * @param key
	 */
	private void createOrder(Integer orderid, Integer count, String bid, CartList ret, CartKey key) {
		boolean insertSuccess = false;
		CartEx ex = new CartEx();
		while(!insertSuccess) {//首先修改图书库存
			Book book = bookService.selectByPrimaryKey(bid);	
			if(book != null) {
				int oldReportory = book.getReportory();
				BookExample bookExample = new BookExample();
				bookExample.createCriteria().andIdEqualTo(bid).andReportoryEqualTo(oldReportory);
				if(book.getReportory() < count) { //库存不足
					ex.setBookid(bid);
					ex.setBookName(book.getName());
					ex.setBookImg(book.getImg());
					ex.setReportory(book.getReportory());
					ret.addCart(ex);
					break;
				}
				
				book.setReportory(oldReportory - count);
				
				int rowsB = bookService.updateByExampleSelective(book, bookExample);
				if(rowsB > 0) { //更新成功
					insertSuccess = true;
					OrderItem orderItem = new OrderItem();
					orderItem.setPrice(book.getPriceSelling());
					orderItem.setBookid(book.getId());
					orderItem.setBookName(book.getName());
					orderItem.setCount(count);
					orderItem.setOrderid(orderid);
					orderItem.setBookImg(book.getImg());
					orderItem.setCreateTime(new Date());
					int rowsO = orderItemService.insertSelective(orderItem);
					if(rowsO > 0 && key != null) {
						cartService.deleteByPrimaryKey(key); //添加订单成功从购物车中去掉
					}
				}
			} else {
				break;
			}
		}	
	}
	
	@RequestMapping(value="/saveOrderItem")
	@ResponseBody
	public String saveItem(OrderItem orderItem, Integer isM, HttpSession session) throws Exception{		
		Ret ret = new Ret();
		
		if(orderItem.getId() != null) {			
			boolean insertSuccess = false;
			while(!insertSuccess) {
				Book book = bookService.selectByPrimaryKey(orderItem.getBookid());
				int oldCount = book.getReportory();
				book.setReportory(oldCount - 1);
				BookExample bookExample = new BookExample();
				bookExample.createCriteria().andIdEqualTo(book.getId()).andReportoryEqualTo(oldCount);
				insertSuccess = bookService.updateByExample(book, bookExample) == 1; //更新成功，
			}
			
		} else {
			orderItem.setModifyTime(new Date());
			orderItemService.updateByPrimaryKeySelective(orderItem);
		}
		
		return JSONRepUtils.serialize(ret, isM);
	}
	
	@RequestMapping(value="/findByIdOrder")
	@ResponseBody
	public String findById(Integer id, Integer isM, HttpSession session)throws Exception{		
		Order order = orderService.selectByPrimaryKey(id);
		OrderEx orderEx = new OrderEx(order);
		OrderItemExample orderItemExample = new OrderItemExample();
		orderItemExample.createCriteria().andOrderidEqualTo(order.getId());
		orderEx.setItems(orderItemService.selectByExample(orderItemExample));
		return JSONUtils.serialize(orderEx);
	}
	
	@RequestMapping("/delOrder")
	@ResponseBody
	public String del(String id,String url, Integer isM, HttpSession session)throws Exception{
		Ret ret = new Ret();
		String[] ids = id.split(",");
		int len = ids.length;
		for(int i = 0; i < len; i++) {
			orderService.deleteByPrimaryKey(Integer.valueOf(ids[i]));
		}
		ret.setSuccess(true);
		return JSONRepUtils.serialize(ret, isM);
	}
	
	@RequestMapping("/cancelOrder")
	@ResponseBody
	public String cancel(Integer id, String userid, Integer isM, HttpSession session) {
		Ret ret = new Ret();
		int rows = orderService.setOrderStatus(1, id, userid);
		if(rows > 0) {
			ret.setSuccess(true);
		}
		return JSONRepUtils.serialize(ret, isM);
	}
	
	@RequestMapping("/handleOrder")
	@ResponseBody
	public String handle(Integer id, String userid, Integer isM, HttpSession session) {
		Ret ret = new Ret();
		int rows = orderService.setOrderStatus(3, id, userid); //设为已出货
		if(rows > 0) {
			ret.setSuccess(true);
		}
		return JSONRepUtils.serialize(ret, isM);
	}
	
	@RequestMapping("/finishOrder")
	@ResponseBody
	public String finish(Integer id, String userid, Integer isM, HttpSession session) {
		Ret ret = new Ret();
		
		int rows = orderService.setOrderStatus(2, id, null);
		if(rows > 0) {
			ret.setSuccess(true);
			//合同数+1
			Order order = orderService.selectByPrimaryKey(id);
			if(order != null) {
				AdminExample example = new AdminExample();
				example.createCriteria().andAppidEqualTo(order.getSid());
				List<Admin> list = adminService.selectByExample(example);
				if(list.size() > 0) {
					Admin a = list.get(0);
					a.setContract(a.getContract() + 1);
					adminService.updateByPrimaryKeySelective(a);
				}
			}
		}
		
		return JSONRepUtils.serialize(ret, isM);
	}
	
	
}

